package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"math/rand"
	"os"
)

func GenerateRandomString(length int) string {
	var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	//charset += time.Now().Format(time.RFC3339Nano)
	if length > len(charset) {
		length = len(charset)
	}

	b := make([]byte, length)
	for i := range b {
		b[i] = charset[rand.Intn(len(charset))]
	}

	return string(b)
}

func Md5Hash(input string) string {
	harsher := md5.New()
	_, err := harsher.Write([]byte(input))
	if err != nil {
		fmt.Println("Failed to calculate MD5 hash")
		return ""
	}
	result := hex.EncodeToString(harsher.Sum(nil))
	return result
}

func GetFileMD5(pathName string) string {
	f, err := os.Open(pathName)
	if err != nil {
		return ""
	}
	defer f.Close()

	md5hash := md5.New()
	if _, err := io.Copy(md5hash, f); err != nil {
		return ""
	}
	has := md5hash.Sum(nil)
	return hex.EncodeToString(has)
}

func GetRandomStr() string {
	base := GenerateRandomString(64)
	return Md5Hash(base)
}

func StringInArray(source string, dest []string) bool {
	for _, v := range dest {
		if source == v {
			return true
		}
	}
	return false
}

// FileExists 检查文件是否存在
func FileExists(filename string) bool {
	_, err := os.Stat(filename)
	return !os.IsNotExist(err)
}
